$(function () {
    /* 初始化加载数据表 */
	$('#operateTeacherDialog').hide();
	$('#showImportTeachersDialog').hide();
	$('#manageClaszsDialog').hide();
    initTeacherGridData();
    initOther();
    $('#picture').bind('change', pictureChange);
});

function initTeacherGridData() {
    $('#teacherDataGrid').datagrid({
        fitColumns: false,
        fit: true,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        rownumbers: false,
        singleSelect: true,
        pagination: true, 
        border: true,
        url: "teacher/all",
        toolbar: '#tb',
//        toolbar: [
//            {
//                text: '新增',
//                iconCls: 'icon-add',
//                handler: function () {
//                    showOperateTeacherDialog("新增");
//                }
//            },
//            '-',
//            {
//                text: '刷新',
//                iconCls: 'icon-reload',
//                handler: function () {
//                    gridReload($('#teacherDataGrid'));
//                }
//            },
//            '-',
//            {
//                text: '导入',
//                iconCls: 'icon-redo',
//                handler: function () {
//                	showImportTeachersDialog($('#teacherDataGrid'));
//                }
//            }
//        ],
//        columns: [
//            [
//                {field: 'name', title: '姓名', align: 'center', width: 40},
//                {field: 'sex', title: '性别', align: 'center', width: 10,
//                    formatter: function (value, row, index) {
//                        return sex[value];
//                    }
//                },
//                {field: 'identityCardNumber', title: '身份证号码', align: 'center', width: 80},
//                {field: 'birthday', title: '生日', align: 'center', width: 30},
//                {field: 'nation', title: '民族', align: 'center', width: 20,
//                    formatter: function (value, row, index) {
//                        return nation[value - 1];
//                    }
//                },
//                {field: 'subject', title: '科目', align: 'center', width: 40},
//                {field: 'grade', title: '任课班级', align: 'center', width: 40},
//                {field: 'operation', title: '操作', align: 'center', width: 80,
//                    formatter: function (value, row, index) {
//                        return "<a class='up' onclick='showOperateTeacherDialog(\"修改\", " + index + ");'>修改</a>" +
//                            "<a class='re' onclick='showDeleteTeacherDialog(" + index + ");'>删除</a>" +
//                            "<a class='fp' onclick='showManageClaszsDialog(" + index + ");'>分配班级</a>";
//                    }
//                }
//            ]
//        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        }, 
        view: detailview,
        detailFormatter:function(index,row){
            var srcUrl = addTimestampToURL('teacher/getTeacherPicture/' + row.id);
        	return '<table><tr>' +
	            '<td rowspan=2 style="border:0"><img style="width:150px;height:150px;" src="' + srcUrl + '"/></td>' +
//	            '<td rowspan=2 style="border:0"><img style="width:150px;height:150px;" onError="imgError(this);" src="' + srcUrl + '"/></td>' +
//	            '<td style="border:0">' +
//	            '<p>任课班级: ' + row.grade + '</p>' +
//	            '</td>' +
//	            '<td style="border:0">' +
//	            '<p>任课班级: ' + row.grade + '</p>' +
//	            '</td>' +
	            '</tr></table>';
        },
//        onSelect: function (rowIndex, rowData) {
//            showTeacherPicture(rowData.id);
//        },
        onLoadSuccess: function() {
        	changeStyle();
        	$('#operateTeacherDialog').show();
        	$('#showImportTeachersDialog').show();
        	$('#manageClaszsDialog').show();
        }
    });
    setDataGridPager($('#teacherDataGrid'));
}

function initOther() {
    extendValiateboxType();
    initComobox($('#sex'), sex);
    initComobox($('#nation'), nation);
//    $('#sex').combobox({
//        valueField: 'id',
//        textField: 'text',
//        panelHeight: 44,
//        data: [
//            {
//                "id": 0,
//                "text": sex[0]
//            },
//            {
//                "id": 1,
//                "text": sex[1]
//            }
//        ]
//    });
//    $('#nation').combobox({
//        valueField: 'id',
//        textField: 'text',
//        panelHeight: 110,
//        data: [
//            {
//                "id": 0,
//                "text": nation[0]
//            },
//            {
//                "id": 1,
//                "text": nation[1]
//            },
//            {
//                "id": 2,
//                "text": nation[2]
//            },
//            {
//                "id": 3,
//                "text": nation[3]
//            },
//            {
//                "id": 4,
//                "text": nation[4]
//            }
//        ]
//    });
  //==================================//
    var $error = $('#error');
    
    var $name = $('#name');
    $name.focusout(function() {
    	if (!validNull($(this).val())) {
    		if ($('#nameNullError').html() == undefined) {
    			$error.append("<span id='nameNullError'>姓名不能为空！&nbsp;&nbsp;</span>");
    		}
    		return;
    	} else {
    		$('#nameNullError').remove();
    	}
    });

    var $idno = $('#identityCardNumber');
    $idno.focusout(function() {
    	if (!validNull($(this).val())) {
    		if ($('#idnoNullError').html() == undefined) {
        		$('#idnoExistsError').remove();
    			$error.append("<span id='idnoNullError'>身份证号不能为空！&nbsp;&nbsp;</span>");
    		}
    		return;
    	} else {
    		$('#idnoNullError').remove();
    	}
    	if (!validIdNo($(this).val())) {
    		if ($('#idnoError').html() == undefined) {
        		$('#idnoExistsError').remove();
    			$error.append("<span id='idnoError'>身份证号格式不正确！&nbsp;&nbsp; ");
    		}
    		return;
    	} else {
    		$('#idnoError').remove();
    	}
    	if ($('#oldIdNo').text() != null && $('#oldIdNo').text() == $("#identityCardNumber").val()) {
    		$('#idnoExistsError').remove();
    		return;
    	}
    	$.ajax({
            type: 'POST',
            data: { "identityCardNumber": $("#identityCardNumber").val() },
            url: "teacher/exists",
            dataType: "json",
            cache: false,
            success: function (data) {
        		$('#idnoExistsError').remove();
                if (true == data.result) {
            		if ($('#idnoExistsError').html() == undefined) {
            			$error.append("<span id='idnoExistsError'>身份证号数据库中已经存在！&nbsp;&nbsp; ");
            			return;
            		}
                }
            }
        });
    });
}

//============================ //
function changeStyle() {
	$('.re').linkbutton({  
	    iconCls: 'icon-remove',
	    plain: true
	});  
	$('.up').linkbutton({  
	    iconCls: 'icon-edit',
	    plain: true
	});  
	$('.fp').linkbutton({  
	    iconCls: 'icon-edit',
	    plain: true
	});  
	$('.sp').linkbutton({  
	    iconCls: 'icon-help',
	    plain: true
	}); 
}

function showOperateTeacherDialog(operateName, index) {
    $('#oldIdNo').remove();
    $('#operateTeacherDialog').dialog({
        title: operateName + "教师信息",
        width: 540,
        height: 330,
        modal: true,
        buttons: [
            {
                text: operateName,
                handler: function (params) {
                    operateTeacher(operateName);
                }
            },
            {
                text: '取消',
                handler: function () {
                    $('#operateTeacherDialog').dialog('close');
                }
            }
        ],
        onClose: function() {
        	$('#error').empty();
            $('#oldIdNo').remove();
        }
    });
    clearOldData();
    if (operateName == '修改') {
        var teacher = getSelectedRow('teacherDataGrid', index);
        $("#id").val(teacher.id);
        $("#name").val(teacher.name);
        $("#sex").combobox('select', teacher.sex);
        $("#nation ").combobox('select', teacher.nation - 1);
        $("#birthday").datebox('setValue', teacher.birthday);
        $("#identityCardNumber").val(teacher.identityCardNumber);
        $("#subject").val(teacher.subject);
        $("#grade").val(teacher.grade);
        $("#nopicture").css("display", "none");
        $("#picturepreview").html("<img src='teacher/getTeacherPicture/" + teacher.id + "' width=150 height=150 />");
        $('#operateTeacherDialog').append("<span id='oldIdNo'>" + teacher.identityCardNumber + "</span>");
    }
}

function clearOldData() {
    $("#id").val("");
    $("#name").val("");
    $("#sex").combobox('setValue', 0);
    $("#nation ").combobox('setValue', 0);
    $("#birthday").datebox('setValue', "");
    $("#identityCardNumber").val("");
    $("#subject").val("");
    $("#grade").val("");
    $("#picture").val("");
    $("#nopicture").css("display", "block");
    $("#picturepreview").html("");
}

function operateTeacher(operationName) {
	if (!($.trim($('#error').html()) == '')) {
		$.messager.alert("警告", "请确保提交内容格式！", "warning");
		return;
	}
	$('#error').empty();
    var $name = $('#name');
    var $idno = $('#identityCardNumber');
	if ($.trim($name.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
	if ($.trim($idno.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
    var tempUrl = "teacher/add";
    if (operationName === '修改') {
        tempUrl = "teacher/update";
    } else {
        $("#id").val(-999);
    }
    $.ajax({
        type: 'POST',
        data: {
            "id": $("#id").val(),
            "identityCardNumber": $("#identityCardNumber").val(),
            "name": $("#name").val(),
            "birthday": $("#birthday").datebox('getValue'),
            "sex": $("#sex").combobox('getValue'),
            "nation": parseInt($("#nation").combobox('getValue')) + 1,
            "subject": $("#subject").val(),
            "grade": $("#grade").val()},
        url: tempUrl,
        dataType: "json",
        cache: false,
        error: function (jqXHR, textStatus, errorThrown) {
            $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        },
        success: function (data) {
            if (data.result > 0) {
                $.messager.alert("操作提示", "老师信息操作完成！", "info", function () {
                    $('#operateTeacherDialog').window("close");
                    gridReload($('#teacherDataGrid'));
                });
            }
        }
    });
}

function showDeleteTeacherDialog(index) {
    $.messager.confirm("警告", "确定删除选中教师？", function (data) {
        if (data) {
        	var teacher = getSelectedRow('teacherDataGrid', index);
        	$.ajax({
        		type: 'POST',
        		data: {
        			"teacherId": teacher.id
        		},
        		url: "teacher/remove",
        		dataType: "json",
        		cache: false,
        		error: function (jqXHR, textStatus, errorThrown) {
        			$.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        		},
        		success: function (data) {
        			if (true == data.result) {
    					gridReload($('#teacherDataGrid'));
        			} else {
                        $.messager.alert("操作提示", "删除教师信息异常！");
                    }
        		}
        	});
        }
    });
}

function showPassword(index) {
    var teacher = getSelectedRow('teacherDataGrid', index);
    $.ajax({
        type: 'POST',
        data: {
        },
        url: "authentication/" + teacher.identityCardNumber,
        dataType: "json",
        cache: false,
        error: function (jqXHR, textStatus, errorThrown) {
            $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        },
        success: function (data) {
            if ("" == data.result) {
                $.messager.alert("操作提示", "未成查询老师密码！", "info");
            } else {
                $.messager.alert("操作提示", "老师[" + teacher.name + "]密码:" + data.result, "info");
            }
        }
    });
}

//function showTeacherPicture(teacherId) {
//    hiddenTeacherPicture();
//    var pictureId = "picture_" + teacherId;
//    $('#' + pictureId).attr('src', addTimestampToURL('teacher/getTeacherPicture/' + teacherId));
//    $('#' + pictureId).show();
//}
//function hiddenTeacherPicture() {
//    $("img[id^='picture_']").hide();
//}

function pictureChange() {
	if (!validUploadJpgFile()) {
		return;
	}
    var sessionId = $.cookie('JSESSIONID');
    $('#pictureForm').form('submit', {
        url: 'teacher/' + sessionId + '/picture',
        success: function (data) {
            var fileName =  $('#picture').val();
            var suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length);
            $("#picturepreview").html("");
            $("#nopicture").css("display", "none");
            var tempUrl = addTimestampToURL('upload/' + sessionId + suffix);
            $("#picturepreview").html("<img src='" + tempUrl + "' width=150 height=150 />");
        }
    });
}

// javaccript-upload-image IE不支持！！使用方法
//function previewImage(e) {
//    var preview = $('#preview_fake');
//    e = e.originalEvent;
//    e.preventDefault();
//    window.loadImage(
//        (e.dataTransfer || e.target).files[0],
//        function (img) {
//            if (img.type === "error") {
////                console.log("Error loading image");
//            } else {
//                preview.children().replaceWith(img);
//                $('img').css('width', '150px');
//                $('img').css('height', '150px');
//            }
//        },
//        {
//            maxWidth: 150,
//            maxHeight: 150
//        }
//    );
//}

function showManageClaszsDialog(index) {
	$('#manageClaszsDialog').show();
    var teacher = getSelectedRow('teacherDataGrid', index);
    $('#currentTeacherId').val(teacher.id);
    $('#currentTeacherType').val(teacher.type);
    var tempUrl = "teacher/" + $('#currentTeacherId').val() + "/all-claszs";
    var searchNotInClassUrl = "teacher/" + $('#currentTeacherId').val() + "/all-notin-claszs";
    $('#manageClaszsDialog').dialog({
        title: "教师[" + teacher.name + "] --> 班级管理",
        width: 842,
        height: 400,
	    iconCls: 'icon-edit',
        modal: true,
        onClose: function() {
        	$('#teachersInClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        	$('#teachersNotInClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        }
    });
    $('#teachersInClaszDataGrid').datagrid({
        title: "已分配班级",
        fitColumns: true,
        fit: true,
        idField: 'id',
        sortName: 'id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: false,
        border: true,
        url: tempUrl,
        columns: [
            [
                {field: 'id', hidden: true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
                {field: 'ck', align: 'center', width: 10, checkbox: true},
                {field: 'name', title: '名称', align: 'center', width: 80},
                {field: 'type', title: '班级类型', align: 'center', width: 40,
                    formatter: function (value, row, index) {
                        return classtype[value];
                    }
                },
                {field: 'createYear', title: '年级', align: 'center', width: 60}
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        }
    });

    $('#teachersNotInClaszDataGrid').datagrid({
        title: "未分配班级",
        fitColumns: true,
        fit: true,
        idField: 'id',
        sortName: 'id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: false,
        border: true,
        url: searchNotInClassUrl,
        toolbar: '#tb-ft',
//        toolbar: '#tb',
//        toolbar: [
//			{
//			  text: '新增',
//			  iconCls: 'icon-add',
//			  handler: function () {
//			      showOperateTeacherDialog("新增");
//			  }
//			},
//			'-',
//			{
//			  text: '刷新',
//			  iconCls: 'icon-reload',
//			  handler: function () {
//			      gridReload($('#teacherDataGrid'));
//			  }
//			},
//			'-',
//			{
//			  text: '导入',
//			  iconCls: 'icon-redo',
//			  handler: function () {
//			  	showImportTeachersDialog($('#teacherDataGrid'));
//			  }
//			}
//		],
        columns: [
            [
                {field: 'id', hidden: true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
                {field: 'ck', align: 'center', width: 10, checkbox: true},
                {field: 'name', title: '名称', align: 'center', width: 80},
                {field: 'type', title: '班级类型', align: 'center', width: 40,
                    formatter: function (value, row, index) {
                        return classtype[value];
                    }
                },
                {field: 'createYear', title: '年级', align: 'center', width: 60}
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        }
    });
}

// 将老师从班级中移除
function removeTeacherFromCLaszs() {
    var ids = [];
    var rows = $('#teachersInClaszDataGrid').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
    }
    if (ids.length > 0) {
        $.messager.confirm("提示", "是否将取消教师分配到选中的班级", function (data) {
            if (data) {
                $.ajax({
                    type: 'GET',
                    url: "teacher/" + $('#currentTeacherId').val() + "/removeclaszs?claszIdsStr=" + ids,
                    dataType: "json",
                    cache: false,
                    error: function (jqXHR, textStatus, errorThrown) {
                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                        $('#teachersInClaszDataGrid').datagrid('unselectAll');
                        $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
                    },
                    success: function (data) {
//                        if (true == data.result) {
//                            $.messager.alert("操作提示", "移除完成！", "info", function () {
                            reloadTeachersInClasz();
                            $('#teachersInClaszDataGrid').datagrid('unselectAll');
                            $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
//                            });
//                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选中班级！");
    }
}

// 分配老师到某些班级
function addTeacherToCLaszs() {
    var ids = [];
    var rows = $('#teachersNotInClaszDataGrid').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
    }
    if (ids.length > 0) {
        $.messager.confirm("提示", "是否将选中的班级分配给此教师", function (data) {
            if (data) {
                $.ajax({
                    type: 'GET',
                    url: "teacher/" + $('#currentTeacherId').val() + "/addclaszs?claszIdsStr=" + ids,
                    dataType: "json",
                    cache: false,
                    error: function (jqXHR, textStatus, errorThrown) {
                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                        $('#teachersInClaszDataGrid').datagrid('unselectAll');
                        $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
                    },
                    success: function (data) {
//                        if (true == data.result) {
//                            $.messager.alert("操作提示", "添加完成！", "info", function () {
                                reloadTeachersInClasz();
                                $('#teachersInClaszDataGrid').datagrid('unselectAll');
                                $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
//                            });
//                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选中班级！");
    }
}

function searchTeacherByName() {
	if (undefined == $("#sName").val() || "" == $("#sName").val() || $.trim($("#sName").val()).length == 0) {
		$('#teacherDataGrid').datagrid({
			url:'teacher/all'
		});
	} else {
		$('#teacherDataGrid').datagrid({
			url:'teacher/teacher-by-name',
		    queryParams:{ name: $("#sName").val()}
		});
	}
}

function reloadTeachersInClasz() {
    $('#teachersInClaszDataGrid').datagrid('reload');
    $('#teachersNotInClaszDataGrid').datagrid('reload');
}

//显示导入界面
function showImportTeachersDialog(needReloadDataGrid) {
$('#importTeachersDialog').dialog({
   width: 462,
   height: 250,
   modal: true,
   content: createFrame("importTeachers"),
   buttons: [
       {
           text: '取消',
           handler: function () {
        	   closeImportTeachersDialog();
           }
       }
   ]
});
}

//关闭导入界面
function closeImportTeachersDialog() {
	$('#importTeachersDialog').dialog('close');
    gridReload($('#teacherDataGrid'));
}

function searchClaszByName() {
    var searchNotInClassUrl = "teacher/" + $('#currentTeacherId').val() + "/all-notin-claszs";
	if (undefined == $("#clasz_sName").val() || "" == $("#clasz_sName").val() || $.trim($("#clasz_sName").val()).length == 0) {
		$('#teachersNotInClaszDataGrid').datagrid({
			url:searchNotInClassUrl
		});
	} else {
		$('#teachersNotInClaszDataGrid').datagrid({
			url: "teacher/" + $('#currentTeacherId').val() + '/all-notin-claszs-byname',
		    queryParams:{ name: $("#clasz_sName").val()}
		});
	}
}
function imgError(obj){
	 obj.src='resources/icons/no_pic.png';
	 obj.onerror = null;//控制onerror事件只触发一次
}